import store from "@/store/index.js";
import crypto from "crypto";
import {
	deviceRptstat,
	deviceOrder,
	errorAdd,
	deviceLease,
	modeList,
	getTx
} from "@/require/api.js";
export default {

    openBluetoothAdapter() {
		let _=this;
		uni.openBluetoothAdapter({
			success: (res) => {
				modeList().then(modeRes=>{
					let mode=[];
					modeRes.data.forEach(item=>{
						mode.push(item.device_mode_name);
						
					});
					if(mode.length>0){
						store.commit('setMode',mode);
					}
					
					_.startBluetoothDevicesDiscovery();
				});
			},
			fail: (res) => {
				errorAdd({
					msg: JSON.stringify(res)
				});
				
				_.getTxF(res,'请开启本机蓝牙');

				if (res.errCode === 10001) {
					//监听蓝牙适配器是否打开，若打开则自动搜索蓝牙设备
					uni.onBluetoothAdapterStateChange(function(res) {
						if (res.available) {
							modeList().then(modeRes=>{
								let mode=[];
								modeRes.data.forEach(item=>{
									mode.push(item.device_mode_name);
									
								});
								if(mode.length>0){
									store.commit('setMode',mode);
								}
								
								_.startBluetoothDevicesDiscovery();
							}); //开启蓝牙设备搜索
						}
					});
				}

			},
		});
	},
	startBluetoothDevicesDiscovery() {

		uni.startBluetoothDevicesDiscovery({

			allowDuplicatesKey: false, //允许重复上报同一个设备
			success: (res) => {
				this.onBluetoothDeviceFound(); //监听新设备事件
			},
			fail: (err) => {
				errorAdd({
					msg: JSON.stringify(err)
				});
				_.getTxF(err,'');
				console.log(err);
			}
		});
	},
	onBluetoothDeviceFound() {

		uni.onBluetoothDeviceFound((res) => {

			res.devices.forEach(device => {

             
			 //    if(device.name!=''){
				// 	console.log(device);
				// } 
			   
			   let shebei=store.state.mode;
				   //过滤掉没有名字的设备
				if (!shebei.includes(device.name)) {
					return
				};
				
				console.log(device);


				let hex = this.ab2hex(device.advertisData);

				hex = hex.toUpperCase();



				hex = hex.split('');
				console.log(hex);

				let data = {};
				let text = hex[4] + hex[5] + ':' +
					hex[6] + hex[7] + ':' + hex[8] + hex[9] + ':' + hex[10] + hex[11] + ':' + hex[12] +
					hex[13] + ':' + hex[14] + hex[15];

				data.mac = text;
				data.deviceId = device.deviceId;
				data.name=device.name;

              
				console.log(data);
				store.commit('setMac', data);
				store.commit('setAevices', device);

				//数组里没有的的就向里面添加数据，保证没有重复   
			})
		});
	},
	createBLEConnection(deviceId) {
		let _ = this;
		uni.createBLEConnection({
			deviceId: deviceId,
			success: (res) => {
				setTimeout(() => {
					uni.stopBluetoothDevicesDiscovery(); //停止搜索蓝牙设备
					store.commit('setDid', deviceId);
					
					let mac = store.state.macsList[store.state.deviceId];
					deviceLease({deviceNumber:mac,type:1}).then(dres=>{
						store.commit('setSkey',dres.data.device.secretKey);
						store.commit('setPassword',dres.data.device.pwd+'');
						_.getBLEDeviceServices(deviceId); //获取服务
					});
				
				}, 1000);
			},
			fail: (err) => {
				errorAdd({
					msg: JSON.stringify(err)
				});
				
				_.getTxF(err,'连接失败,请重试');
				
				
				console.log("连接失败----", err);
				return
			}
		})
	},
	getBLEDeviceServices(deviceId) {

		uni.getBLEDeviceServices({
			deviceId: deviceId, //连接设备的devideid值
			success: (res) => {
				console.log('获取服务', res);

				res.services.forEach(item => {
					this.getBLEDeviceCharacteristics(deviceId, item.uuid);
				})
			},
			fail: (err) => {
				errorAdd({
					msg: JSON.stringify(err)
				});
				console.log("获取服务失败----", err);
				return
			}
		})
	},

	getBLEDeviceCharacteristics(deviceId, serviceId) {
		uni.getBLEDeviceCharacteristics({ //设备id与服务id必须要给,特征值id先不用获取，直接写死
			deviceId,
			serviceId,
			success: (res) => {
				console.log('获取特征指', res);
				let write = false;
				let notify = false;
				res.characteristics.forEach(item => {

					if (item.properties.write) {
						write = item.uuid;
					}
					if (item.properties.notify) {
						notify = item.uuid;
					}

				});
				if (write && notify) {
					store.commit('setSid', serviceId);
					store.commit('setCharId', write);
					store.commit('setCharIds', notify);
					console.log(store.state);
					this.setWrite();
				}
			},
			fail: (res) => {
				/* errorAdd({
					msg: JSON.stringify(res)
				}); */
				console.error('获取蓝牙设备特征值失败', res)
			}
		})
	},
	setWrite() {

		uni.notifyBLECharacteristicValueChange({
			deviceId: store.state.deviceId,
			serviceId: store.state.serviceId,
			characteristicId: store.state.characteristicIds,
			state: true, //是否启用notify通知
			success: (res) => {
				console.log(res, '开启通知');
				this.listenValueChange();
			},
			fail: (error) => {
				errorAdd({
					msg: JSON.stringify(error)
				});
				console.log(error, '开启通知失败');
			}
		})
		//添加断开验证
		uni.onBLEConnectionStateChange(function(res) {
			if (!res.connected) {
				console.log("设备已断开")
			}
		})
		let ml = '06010101000000000000000000000000'
		let data = Buffer.from(ml, 'hex')
		let sKey = Buffer.from(store.state.sKey, 'hex')
		let ent = this.encrypts(data, sKey)
		let ents = '40980A4246DA9214764601E01AF7A5A3';
		//点击发送命令（连接上后就发送连接指令为了清空设备上的数量）
		setTimeout(() => {
			this.writeValue(ent);
		}, 1000)
	},
	encrypts(sSrc, sKey) {
		try {

			const cipher = crypto.createCipheriv('aes-128-ecb', sKey, '');

			cipher.setAutoPadding(false);

			let encrypted = cipher.update(sSrc);
			encrypted = Buffer.concat([encrypted, cipher.final()]);

			let text = '';
			encrypted.forEach(res => {
				text += this.dec2hex(res);
			});

			return text.toUpperCase();
		} catch (ex) {
			console.log(ex)
			return null;
		}
	},
	dec2hex(dec, len = 2) { //10进制转16进制补0
		var hex = "";
		while (dec) {
			var last = dec & 15;
			hex = String.fromCharCode(((last > 9) ? 55 : 48) + last) + hex;
			dec >>= 4;
		}
		if (len) {
			while (hex.length < len) hex = '0' + hex;
		}
		return hex;
	},
	decrypt(sSrc, sKey, type = 1) {
		
			const decipher = crypto.createDecipheriv('aes-128-ecb', sKey, Buffer.alloc(0));
			decipher.setAutoPadding(false);
			let decrypted = decipher.update(sSrc);
			decrypted = Buffer.concat([decrypted, decipher.final()]);

			let text = '';
			decrypted.forEach(res => {
				text += this.dec2hex(res);
			});
			text = text.toUpperCase();
			if (type == 1) {
				return text;
			} else {
				let array = [];
				decrypted.forEach(res => {
					array.push(this.dec2hex(res).toUpperCase());
				});
				return array;
			}
			return null;
		
	},

	listenValueChange() {

		uni.onBLECharacteristicValueChange(res => {
			// 结果
			
			console.log(res);

			let val = this.ab2hex(res.value);
			console.log(val.length);
			if(val&&val.length>32){
				let jian=val.length-32;
				val=val.substr(0,val.length-jian);
			}

			let data = Buffer.from(val, 'hex');
			console.log(data);

			let jm = Buffer.from(store.state.sKey, 'hex');
			console.log(jm);

			let lm = this.decrypt(data, jm, 2);

			console.log(lm);

           if(lm){
			   errorAdd({msg:JSON.stringify(lm)});
		   }

			var type = store.state.type;

			let mac = store.state.macsList[store.state.deviceId];
			if (lm[0] == '02' && lm[1] == '02' && lm[2] == '01') {
				    if(lm[3]){
						deviceRptstat({
							mac: mac,
							power: parseInt(lm[3],16),
							lockstat: 4
						}).then(res => {
						
						});
					}
					
				return true;
			}

           
			if (lm[0] == '05' && lm[1] == '02' && lm[2] == '01') {
           
				if (type == 1) {
					
					
						
					
						uni.hideLoading();
						uni.closeBluetoothAdapter({

						});
						uni.reLaunch({
							url: '/pages/lock/success'
						})
					
				}

				if (type == 3) {
					uni.closeBluetoothAdapter({
					});
					uni.hideLoading();
					store.commit('setList', store.state.newList + 1);	
				}
			}

			if (lm[0] == '05' && lm[1] == '0F' && lm[2] == '02') {
				console.log(lm);
				
				
				if (lm[3]!='01'||lm[4]!='01') {
					uni.hideLoading();
					uni.showToast({
						title: '检测到锁未关,请关锁',
						icon: 'none'
					})
					uni.closeBLEConnection({
						deviceId: store.state.deviceId
					});
					return true;
				}
				deviceRptstat({
					lockstat: 1,
					mac: mac
				}).then(res => {
					console.log(res);
					if (res.code != 200) {
						uni.hideLoading();
						uni.closeBLEConnection({
							deviceId: store.state.deviceId
						});
						uni.showToast({
							title: res.message,
							icon: 'none'
						})
						return true;
					}
					uni.showToast({
						title: '操作成功',
						icon: 'none'
					});
					uni.closeBluetoothAdapter({

					});
					store.commit('setList', store.state.newList + 1);
					deviceOrder({
						page: 1,
						limit: 10,
						status: 0,
						materials: 'accompanyingBed'
					}).then(res => {
						let data = res.data;
						if (data.list && data.list.length == 1) {
							store.commit('setOrder', data.list[0]);
						} else {
							store.commit('setOrder', '');
						}
					});

					setTimeout(() => {
						uni.navigateBack({
							delta: 1
						})

					}, 1000)

				});
			}
			
			if (lm[0] == '06' && lm[1] == '02' && (lm[2] == '08'||lm[2]=='0C')) {
           
                  let _=this;
				//开锁050106 查询状态050E0101检测电量02010101
				if (type == 1 || type == 3) {
					
					
						let password=store.state.password;
						console.log('当前密码:'+password);
						
						let ks = '050106' + password + (lm[3] + '') + (lm[4] + '') + (lm[5] + '') + (lm[6] +
							'') + '010101';
						console.log(ks);
						
						let ksDatas = Buffer.from(ks, 'hex');
						let ksEnt = _.encrypts(ksDatas, jm);
						
						setTimeout(() => {
							_.writeValue(ksEnt);
						}, 1000)
					
				}

				if (type == 2) {
					let cx = '050E0101' + (lm[3] + '') + (lm[4] + '') + (lm[5] + '') + (lm[6] + '') +
						'0000000000000000';

					let cxDatas = Buffer.from(cx, 'hex');
					let cxEnt = this.encrypts(cxDatas, jm);

					setTimeout(() => {
						this.writeValue(cxEnt);
					}, 1000)
				}

				let dian = '02010101' + (lm[3] + '') + (lm[4] + '') + (lm[5] + '') + (lm[6] + '') +
					'0000000000000000';

				let dianDatas = Buffer.from(dian, 'hex');
				let dianEnt = this.encrypts(dianDatas, jm);

				setTimeout(() => {
					this.writeValue(dianEnt);
				}, 300)
			}
		})
	},
	writeValue(msg) {

		let buffer = this.string2buffer(msg);

		uni.writeBLECharacteristicValue({
			deviceId: store.state.deviceId,
			serviceId: store.state.serviceId,
			characteristicId: store.state.characteristicId,
			value: buffer,
			success: (res) => {

				console.log('发送数据 Success', res);
				return;
			},
			fail: (res) => {
				console.log('发送数据 fail', res)
			},
			complete: (res) => {}
		})
	},
	string2buffer(str) {
		let val = ""
		if (!str) return;
		let length = str.length;
		let index = 0;
		let array = []
		while (index < length) {
			array.push(str.substring(index, index + 2));
			index = index + 2;
		}
		val = array.join(",");
		// 将16进制转化为ArrayBuffer
		return new Uint8Array(val.match(/[\da-f]{2}/gi).map(function(h) {
			return parseInt(h, 16)
		})).buffer
	},
	hexCharCodeToStr(hexCharCodeStr) {
		var trimedStr = hexCharCodeStr.trim();
		var rawStr = trimedStr.substr(0, 2).toLowerCase() === "0x" ? trimedStr.substr(2) : trimedStr;
		var len = rawStr.length;
		if (len % 2 !== 0) {
			alert("存在非法字符!");
			return "";
		}
		var curCharCode;
		var resultStr = [];
		for (var i = 0; i < len; i = i + 2) {
			curCharCode = parseInt(rawStr.substr(i, 2), 16);
			resultStr.push(String.fromCharCode(curCharCode));
		}
		return resultStr.join("");
	},
	ab2hex(buffer) {
		const hexArr = Array.prototype.map.call(
			new Uint8Array(buffer),
			function(bit) {
				return ('00' + bit.toString(16)).slice(-2)
			}
		)
		return hexArr.join('')
	},
	hexToString(hex) {
		let str = "";
		for (let i = 0; i < hex.length; i += 2) {
			const charCode = parseInt(hex.substr(i, 2), 16);
			str += String.fromCharCode(charCode);
		}
		return str;
	},
	toFail(msg) {
		uni.hideLoading();
		uni.showToast({
			title: msg,
			icon: 'none'
		})
	},
	async getTxF(e,msg){
		let parm={};
		if(e.errno){
			parm.code=e.errno;
		}
		if(e.errMsg){
			parm.msg=e.errMsg;
		}
	let {data}=await getTx(parm);
	if(data&&data.tx){
		msg=data.tx;
	}
	if(!msg) return;
	uni.showModal({
		title: '提示',
		content: msg,
		showCancel: false,
		success() {
			
		}
	});
	}
}